<template>
  <div>
    <!-- title -->
    <PageTitle>
      {{ $t("menu.M_12688000") }}
    </PageTitle>
    <!-- body -->
    <el-card
      shadow="never"
      :body-style="{ padding: '0px' }"
      @current-change="currentChangeHandle"
      :page-size="pageSize"
      :total="totalPage"
      :current-page="pageIndex"
    >
      <el-form class="p-4" inline>
        <el-form-item>
          <el-input
            maxlength="64"
            v-model="condition"
            @blur="() => (condition = condition.trim())"
            :placeholder="$t('user.query_condition')"
            clearable
            @clear="fetchData"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="w-8" @click="fetchData((pageIndex = 1))">
            <svg-icon icon-class="search" class="text-lg" />
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            v-if="isAuth('12688000.MANAGE')"
            type="primary"
            class="w-8"
            @click="handleAdd"
          >
            <svg-icon icon-class="plus" class="text-lg" />
          </el-button>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button style="border: none" type="primary" class="w-8" size="medium">
            <table-column-filter
              :list="settingList"
              :default-setting="defaultSettings"
              v-model:settings="settings"
              domain="user.manage"
            />
          </el-button>
        </el-form-item>
      </el-form>

      <el-table
        :show-overflow-tooltip="true"
        v-loading="listLoading"
        :data="tableData"
        stripe
      >
        <!--        <el-table-column prop="username" align="left" width="70px">-->
        <!--          <template v-slot="{row}">-->
        <!--            <div-->
        <!--              class="user-list-avatar"-->
        <!--            >-->
        <!--              <img-->
        <!--                :src="getLogo(row.logoUrl)"-->
        <!--              />-->
        <!--            </div>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column :label="$t('user.username')" prop="username" />
        <el-table-column
          v-if="showHeader('characterCode')"
          key="characterCode"
          :label="$t('user.user_type')"
          prop="characterCode"
        />
        <el-table-column :label="$t('user.contact_name')" prop="name" />
        <el-table-column
          v-if="showHeader('orgName')"
          key="orgName"
          :label="$t('user.organization')"
          prop="orgName"
        />
        <el-table-column :label="$t('user.status')" prop="status">
          <template v-slot="{ row }">
            <el-tag type="warning" v-if="row.status === 0">{{
              statusFilter(row.status)
            }}</el-tag>
            <el-tag type="success" v-if="row.status === 1">{{
              statusFilter(row.status)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-if="showHeader('creTime')"
          :label="$t('common.createTime')"
          key="creTime"
          prop="creTime"
        >
          <template v-slot="{ row }">
            <div :title="timeFilter(row.creTime)">
              {{ dateFilter(row.creTime) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="showHeader('lastLoginTime')"
          :label="$t('user.last_login_time')"
          key="lastLoginTime"
          prop="lastLoginTime"
        >
          <template v-slot="{ row }">
            <div :title="timeFilter(row.lastLoginTime)">
              {{ dateFilter(row.lastLoginTime) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="isAuth('12688000.MANAGE') || isAuth('12688000.COUNTRY_CONFIG_MANAGE')"
          width="75"
        >
          <template v-slot="scope">
            <el-dropdown
              v-if="
                scope.row.username != loginUserName &&
                scope.row.managerFlag != 1 &&
                (isAuth('12688000.MANAGE') || isAuth('12688000.COUNTRY_CONFIG_MANAGE'))
              "
              @command="handleClick"
              class="align-middle"
              trigger="click"
            >
              <el-button text class="w-8">
                <svg-icon icon-class="MoreFilled" />
              </el-button>

              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-if="isAuth('12688000.MANAGE')"
                    :command="beforeHandleCommand('edit', scope.row)"
                  >
                    <svg-icon icon-class="Edit" />
                    {{ $t("common.modify") }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="scope.row.status === 1 && isAuth('12688000.MANAGE')"
                    :command="beforeHandleCommand('lock', scope.row)"
                  >
                    <svg-icon icon-class="Lock" />
                    {{ $t("user.lock") }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="scope.row.status === 0 && isAuth('12688000.MANAGE')"
                    :command="beforeHandleCommand('unlock', scope.row)"
                  >
                    <svg-icon icon-class="Unlock" />
                    {{ $t("user.unlock") }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="isAuth('12688000.MANAGE')"
                    :command="beforeHandleCommand('delete', scope.row)"
                  >
                    <svg-icon icon-class="Delete" />
                    <span>{{ $t("common.delete") }}</span>
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="isAuth('12688000.COUNTRY_CONFIG_MANAGE')"
                    :command="beforeHandleCommand('manageCountry', scope.row)"
                  >
                    <svg-icon icon-class="MapLocation" />
                    <span>{{ $t("common.manage_country_config") }}</span>
                  </el-dropdown-item>
                </el-dropdown-menu></template
              >
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <user-add
      ref="userDialog"
      :type="operationType"
      :user-id="editUserId"
      @submit="fetchData"
      v-model="addUserVisible"
      :title="editUserId ? $t('user.edit_user_title') : $t('user.add_user_title')"
    ></user-add>
    <manage-country ref="manageCountry" v-model="manageCountryVisible"></manage-country>
  </div>
</template>

<script>
import TableColumnFilter from "@/components/page-setting/table-column-filter";
import { isAuth } from "@/utils";
import { deleteUser, getUserPage, lockUser, unlockUser } from "@/api/user";
import { timeFilter, dateFilter } from "@/filters/index";
import UserAdd from "./user-add";
import ManageCountry from "./components/manage-country";
import PageTitle from "@/components/PageTitle/index.vue";
export default {
  components: {
    UserAdd,
    TableColumnFilter,
    ManageCountry,
    PageTitle,
  },
  data() {
    return {
      settings: {
        conditions: [],
        columns: [],
      },
      loginUserName: "",
      tableData: [],
      listLoading: false,
      selectedData: [],
      paginationShow: true,
      condition: "",
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      operationType: "",
      editUserId: "",
      addUserVisible: false,
      manageCountryVisible: false,
    };
  },
  mounted() {
    const userInfo = JSON.parse(
      localStorage.getItem(this.$store.getters.keys.storage.username)
    );
    this.loginUserName = userInfo.username;
    this.fetchData();
  },
  computed: {
    settingList() {
      return {
        columns: [
          {
            title: this.$t("user.user_type"),
            code: "characterCode",
          },
          {
            title: this.$t("user.organization"),
            code: "orgName",
          },
          {
            title: this.$t("common.createTime"),
            code: "creTime",
          },
          {
            title: this.$t("user.last_login_time"),
            code: "lastLoginTime",
          },
        ],
      };
    },
    defaultSettings() {
      return {
        columns: [
          "lastLoginTime",
          // this.$t('common.online'),
        ],
      };
    },
  },
  methods: {
    isAuth,
    statusFilter(status) {
      const statusMap = {
        0: "Locked",
        1: "Valid",
      };
      return statusMap[status];
    },
    timeFilter,
    dateFilter,
    showHeader(label) {
      var list = this.settings["columns"];
      return list ? list.includes(label) : false;
    },
    showFormItem(label) {
      var list = this.settings["conditions"];
      return list ? list.includes(label) : false;
    },
    fetchData() {
      this.editUserId = "";
      this.listLoading = true;
      getUserPage({
        pageNo: this.pageIndex,
        pageSize: this.pageSize,
        status: "",
        condition: this.condition,
      })
        .then((res) => {
          this.listLoading = false;
          this.tableData = res.data;
          this.totalPage = res.rows;
        })
        .catch((e) => {
          this.$confirmError(e);
          this.listLoading = false;
        });
    },
    showModify(row) {
      var username = this.$store.state.user.name;
      if (username === row.username) {
        return false;
      }
      return row.userId !== 1;
    },
    showLock(row) {
      var username = this.$store.state.user.name;
      if (username === row.username) {
        return false;
      }
      return row.status === 1 && row.userId !== 1;
    },
    showUnLock(row) {
      var username = this.$store.state.user.name;
      if (username === row.username) {
        return false;
      }
      return row.status === 0 && row.userId !== 1;
    },
    handleLock(row) {
      this.$confirm(
        this.$t("user.sure_to_lock_user") + `[${row.email}]?`,
        this.$t("common.tips"),
        {
          confirmButtonText: this.$t("common.confirm"),
          cancelButtonText: this.$t("common.cancel"),
          type: "warning",
        }
      ).then(() => {
        lockUser(row.userId)
          .then((res) => {
            this.$message({
              message: this.$t("user.lock_success"),
              type: "success",
            });
            this.fetchData();
          })
          .catch(this.$confirmError);
      });
    },
    handleUnlock(row) {
      this.$confirm(
        this.$t("user.sure_to_unlock_user") + `[${row.email}]?`,
        this.$t("common.tips"),
        {
          confirmButtonText: this.$t("common.confirm"),
          cancelButtonText: this.$t("common.cancel"),
          type: "warning",
        }
      ).then(() => {
        unlockUser(row.userId)
          .then((res) => {
            this.$message({
              message: this.$t("user.unlock_success"),
              type: "success",
            });
            this.fetchData();
          })
          .catch(this.$confirmError);
      });
    },
    handleClick(val) {
      let command = val.command;
      let row = val.row;
      if (command === "edit") {
        this.handleEdit(row);
      } else if (command === "lock") {
        this.handleLock(row);
      } else if (command === "unlock") {
        this.handleUnlock(row);
      } else if (command === "delete") {
        this.handleDelete(row);
      } else if (command === "manageCountry") {
        this.showManageCountryDialog(row.userId);
      }
    },
    beforeHandleCommand(command, row) {
      return {
        row: row,
        command: command,
      };
    },
    handleEdit(row) {
      this.operationType = "Update";
      this.editUserId = row.userId;
      this.addUserVisible = true;
      this.$refs.userDialog.init(row.userId);
    },
    handleDelete(row) {
      this.$confirm(this.$t("user.delete_tip", { username: row.username }), "", {
        confirmButtonText: this.$t("common.confirm"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      }).then(() => {
        deleteUser(row.userId)
          .then((res) => {
            this.$message.success(this.$t("common.operate_success"));
            this.fetchData();
          })
          .catch((e) => {
            this.$confirmError(e);
          });
      });
    },
    handleAdd() {
      this.addUserVisible = true;
      this.editUserId = "";
      this.$refs.userDialog.init("");
    },
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.fetchData();
    },
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.fetchData();
    },
    showManageCountryDialog(userId) {
      this.manageCountryVisible = true;
      this.$nextTick(() => {
        this.$refs.manageCountry.init(userId);
      });
    },
  },
};
</script>

<style lang="scss">
.terminal-list {
  .el-table .cell {
    /* height: 30px !important; */
  }
}
</style>

<style lang="scss" scoped>
.query-button {
  margin-left: 30px;
}
.user-list-avatar {
  width: 43.8px;
  height: 43.8px;
  border-radius: 60px;
  overflow: hidden;
  margin: 5px;
  img {
    margin-right: 5px;
    border-radius: 50%;
  }
}
.pagination-wrapper {
  text-align: right;
}
</style>
